const jwt = require("jsonwebtoken");
const fs = require("fs");
const path = require("path");

const { mainPool, userPool } = require("./config/databases");

const usersPath = path.join(__dirname, "users.json");
const SECRET_KEY = "your-secret-key";


async function loginHandler(req, res) {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith("Bearer ")) {
    return res.status(400).json({ message: "缺少 access_token" });
  }

  const accessToken = authHeader.split(" ")[1];

  try {
    const verifyURL = `https://gf-net.cn/auth/auth_getinfo?access_token=${accessToken}&app_name=gf_wiki`;
    const response = await fetch(verifyURL);
    const data = await response.json();

    if (data.code !== 200) {
      return res.status(401).json({ message: "access_token 无效" });
    }

    const { name, no, sign } = data;
    
    // 从用户数据库查询用户信息
    let userRows;
    try {
      [userRows] = await userPool.query("SELECT * FROM users WHERE user_id = ? OR username = ?", [
        no, name
      ]);
      console.log('[Auth] 用户数据库查询结果:', userRows);
    } catch (dbError) {
      console.error('[Auth] 用户数据库查询失败:', dbError);
      // 如果用户数据库查询失败，尝试从本地数据库查询
      [userRows] = await mainPool.query("SELECT user_id as id FROM users WHERE user_id = ?", [no]);
    }
    
    if (!userRows || !userRows.length) {
      return res.status(403).json({ message: "用户不存在" });
    }

    const userInfo = {
      username: name,
      userId: no,
      userDbId: userRows[0].id || userRows[0].user_id,
    };

    const jwtToken = jwt.sign(userInfo, SECRET_KEY, { expiresIn: "3d" });

    res.json({
      token: jwtToken,
      userInfo,
      sign,
    });
  } catch (err) {
    console.error("认证请求失败:", err);
    return res.status(500).json({ message: "认证失败，请稍后再试" });
  }
}

function authMiddleware(allowedRoles = []) {
  return (req, res, next) => {
    let token = null;

    const authHeader = req.headers.authorization;
    if (authHeader && authHeader.startsWith("Bearer ")) {
      token = authHeader.split(" ")[1]; // 从 Bearer 头中提取
    } else if (req.query.token) {
      token = req.query.token; // 从 URL 参数中提取
    }

    if (!token) {
      return res.status(401).json({ message: "Missing token" });
    }

    try {
      // const token = authHeader.split(" ")[1];
      const decoded = jwt.verify(token, SECRET_KEY);

      req.user = decoded;
      console.log("用户:", req.user.username || req.user.userId || "未知用户"  );
      next();
    } catch (err) {
      res.status(401).json({ message: "Invalid token" });
    }
  };
}

module.exports = { loginHandler, authMiddleware };
